package computer.controllers;

import com.mysql.cj.x.protobuf.Mysqlx;
import computer.business.LineItem;
import computer.business.Product;
import computer.business.RootUser;
import computer.data.DBUtil;
import computer.data.DataSourceUtils;
import computer.data.ProductDB;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.apache.logging.log4j.core.util.Integers;
import org.eclipse.tags.shaded.org.apache.bcel.generic.Select;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/CRUDController/*")
public class CRUDController extends HttpServlet {
    private void SelectALLProduct(HttpServletRequest request, HttpServletResponse response) {

        String products = ProductDB.selectProducts();
        request.setAttribute("allProduct", products);

    }

    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String requestURI = request.getRequestURI();

        SelectALLProduct(request, response);

        System.out.println("CatalogController request URI = " + requestURI);
        String url = "";

        if (requestURI.endsWith("/login")) {
            url = loginRoot(request, response);
        }
        HttpSession session = request.getSession();
        RootUser rootUser = (RootUser) session.getAttribute("rootUser");

        if(rootUser == null) {
            url = "/CRUDCatalog/login.jsp";
        } else if (requestURI.endsWith("/insertCatalog")) {
            url = insertCatalog(request, response);
        } else if (requestURI.endsWith("/deleteCatalog")) {
            url = deleteCatalog(request, response);
        } else if (requestURI.endsWith("/updateCatalog")) {
            url = updateCatalog(request, response);
        } else if (requestURI.endsWith("/selectCatalog")) {
            url = selectCatalog(request, response);
        }

        getServletContext()
                .getRequestDispatcher(url)
                .forward(request, response);
    }


    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String requestURI = request.getRequestURI();

        SelectALLProduct(request, response);
        System.out.println("CatalogController request URI = " + requestURI);
        String url = "";

        HttpSession session = request.getSession();
        RootUser rootUser = (RootUser) session.getAttribute("rootUser");

        if(rootUser == null) {
            url = "/CRUDCatalog/login.jsp";
        } else if (requestURI.endsWith("/insertCatalog")) {
            url = "/CRUDCatalog/insertCatalog.jsp";
        } else if (requestURI.endsWith("/deleteCatalog")) {
            url = "/CRUDCatalog/deleteCatalog.jsp";
        } else if (requestURI.endsWith("/updateCatalog")) {
            url = "/CRUDCatalog/updateCatalog.jsp";
        } else if (requestURI.endsWith("/selectCatalog")) {
            url = "/CRUDCatalog/selectCatalog.jsp";
        }

        getServletContext()
                .getRequestDispatcher(url)
                .forward(request, response);
    }

    private String selectCatalog(HttpServletRequest request, HttpServletResponse response) {

        return null;
    }

    private String updateCatalog(HttpServletRequest request, HttpServletResponse response) {
        return null;
    }

    private String deleteCatalog(HttpServletRequest request, HttpServletResponse response) {
        return null;
    }

    private String insertCatalog(HttpServletRequest request, HttpServletResponse response) {

        String code = request.getParameter("ProductCode");
        String description = request.getParameter("ProductDescription");
        double price = Double.parseDouble(request.getParameter("ProductPrice"));

        Product product = new Product();
        product.setCode(code);
        product.setDescription(description);
        product.setPrice(price);

        String result = ProductDB.insertProduct(product);

        if(result != "OK") {
            result = "增加失败，请重试！";

            request.setAttribute("result", result);
            return "/CRUDCatalog/insertImpl.jsp";
        }

        SelectALLProduct(request, response);
        result = "增加商品成功！增加的商品为：" + "{" +
                "商品码='" + code + '\'' +
                ", 商品介绍='" + description + '\'' +
                ", price=" + price +
                '}';

        request.setAttribute("result", result);

        return "/CRUDCatalog/insertCatalog.jsp";
    }


    private String loginRoot(HttpServletRequest request, HttpServletResponse response) {

        String rootName = request.getParameter("rootName");
        String rootPassword = request.getParameter("rootPassword");

        Connection connection = null;
        PreparedStatement ps = null;
        ResultSet rs = null;

        String query = "SELECT * FROM rootUsers WHERE rootName = ? AND rootPassword = ?";

        try {
            connection = DataSourceUtils.getConnection();
            ps = connection.prepareStatement(query);
            ps.setString(1, rootName);
            ps.setString(2, rootPassword);
            rs = ps.executeQuery();
            if (rs.next()) {
                RootUser root = new RootUser();
                root.setRootName(rs.getString("rootName"));
                root.setRootPassword(rs.getString("rootPassword"));
                request.getSession().setAttribute("rootUser", root);

                return "/CRUDCatalog/index.jsp";
            } else {

                String message;
                message = "此后台管理员不存在. <br>"
                        + "请重新输入.";
                request.setAttribute("message", message);
                return "/CRUDCatalog/login.jsp";
            }
        } catch (SQLException e) {
            System.out.println(e);
            String message;
            message = "此后台管理员不存在. <br>"
                    + "请重新输入.";
            request.setAttribute("message", message);
            return "/CRUDCatalog/login.jsp";
        } finally {
            DBUtil.closeResultSet(rs);
            DBUtil.closePreparedStatement(ps);
            DataSourceUtils.freeConnection(connection);
        }

    }

}
